package name.marz.to.go.ahg.mhbk.executer;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import name.marz.to.go.ahg.common.util.HttpUtil;
import name.marz.to.go.ahg.common.util.LogUtil;
import name.marz.to.go.ahg.core.AutoGetterHttpClient;
import name.marz.to.go.ahg.core.Parameters;
import name.marz.to.go.ahg.core.executer.AbstractPostExecuter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class MHBKDetailDownloader extends AbstractPostExecuter<File> {
	private final Document doc;
	private final ResponseHandler<File> handler;
	protected File file;
	private static final Logger log = Logger.getLogger(MHBKDetailDownloader.class.getName());

	public class MHBKDetailResponseHandler implements ResponseHandler<File> {
		private final File file;
		private String charset = "UTF-8";

		public MHBKDetailResponseHandler(File file) {
			this.file = file;
		}

		public MHBKDetailResponseHandler(File file,String charset) {
			this.file = file;
			this.charset = charset;
		}

		
		@Override
		public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
			log.info(response.getStatusLine().toString());
			HttpEntity entity = response.getEntity();
			LogUtil.log(Level.FINE, response.getAllHeaders(),"response header");
			List<String> records = new ArrayList<String>();
			log.info("CSV変換中");
			// 明細のテーブル部分取り出し
			Document doc = Jsoup.parse(EntityUtils.toString(entity,charset));
			log.finer("doc="+doc.html());
			Element elem = doc.getElementsContainingOwnText("日付").first().parent().parent().parent().parent();
			Elements trs = elem.getElementsByTag("tr");
			for (Element tr : trs) {
				Elements tds = tr.getElementsByTag("td");
				StringBuffer rbuf = new StringBuffer();
				if ( tds.size() == 0) continue;
				rbuf.append(tds.get(0).text().trim());	// 日付
				rbuf.append("\t").append(tds.get(1).text().replace(",","").replace("円","").trim());	// 出金
				rbuf.append("\t").append(tds.get(2).text().replace(",","").replace("円","").trim());	// 入金
				rbuf.append("\t").append(tds.get(3).text().trim());	// 内容
				records.add(rbuf.toString());
				log.finer("detail line="+rbuf.toString());
			}
			// ファイルに書き込み
			log.info("ファイルに書き込み中 "+file.getPath());
			PrintWriter writer = new PrintWriter(file);
			for (String  s : records) {
				writer.println(s);
			}
			writer.flush();
			writer.close();
			EntityUtils.consume(entity);
			log.info("ファイルに書き込み終了");
			return file;
		}
	}

	public MHBKDetailDownloader(URI uri, final AutoGetterHttpClient client,final Document doc, final File file) {
		super(uri, client,"明細照会");
		this.file = file;
		this.doc = doc;
		this.handler = new MHBKDetailResponseHandler(file,client.getDefaultCharset());
	}

	@Override
	protected List<NameValuePair> getRequestParameters() {
		Parameters p = HttpUtil.getParametersFromInputTags(doc);
		Parameters sel_p = HttpUtil.getParametersFromSelectTags(doc);
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(p.getNameValuePair("_LUID"));
		params.add(sel_p.getNameValuePair("lstAccSel"));
		params.add(p.getNameValuePair("POSTKEY"));
		params.add(p.getNameValuePair("_TOKEN"));
		params.add(p.getNameValuePair("_SUBINDEX"));
		params.add(p.getNameValuePair("_FORMID"));
		params.add(p.getNameValuePair("_TARGETID"));
		params.add(p.getNameValuePair("_FRAMEID"));
		
		params.add(sel_p.getNameValuePair("lstTargetMnthSel"));

		params.add(new BasicNameValuePair("rdoInqMtdSpec","2"));
		params.add(sel_p.getNameValuePair("lstDateToYear"));
		params.add(sel_p.getNameValuePair("lstDateFrmYear"));
		params.add(sel_p.getNameValuePair("lstDateToMnth"));
		params.add(sel_p.getNameValuePair("lstDateFrmMnth"));
		params.add(sel_p.getNameValuePair("lstDateFrmDay"));
		params.add(sel_p.getNameValuePair("lstDateToDay"));
//	       <input type="button" value="照会" onclick="doTransaction('/ACCHST0400001B',null,false,null,this.form,null,null);" tabindex="200" class="shortest" /> 
		//		09/06/14 11:35:43 FINE LogUtil [log] param[0]=_LUID=
//				09/06/14 11:35:43 FINE LogUtil [log] param[1]=lstTargetMnthSel=null
//				09/06/14 11:35:43 FINE LogUtil [log] param[2]=lstAccSel=0
//				09/06/14 11:35:43 FINE LogUtil [log] param[3]=POSTKEY=201409060065968000005
//				09/06/14 11:35:43 FINE LogUtil [log] param[4]=lstDateToYear=2014
//				09/06/14 11:35:43 FINE LogUtil [log] param[5]=lstDateFrmYear=2014
//				09/06/14 11:35:43 FINE LogUtil [log] param[6]=_TOKEN=1409970990760
//				09/06/14 11:35:43 FINE LogUtil [log] param[7]=_SUBINDEX=
//				09/06/14 11:35:43 FINE LogUtil [log] param[8]=rdoInqMtdSpec=2
//				09/06/14 11:35:43 FINE LogUtil [log] param[9]=_FORMID=ACCHST_04000B
//				09/06/14 11:35:43 FINE LogUtil [log] param[10]=lstDateToDay=6
//				09/06/14 11:35:43 FINE LogUtil [log] param[11]=_TARGETID=root
//				09/06/14 11:35:43 FINE LogUtil [log] param[12]=lstDateToMnth=9
//				09/06/14 11:35:43 FINE LogUtil [log] param[13]=lstDateFrmMnth=7
//				09/06/14 11:35:43 FINE LogUtil [log] param[14]=lstDateFrmDay=1
//				09/06/14 11:35:43 FINE LogUtil [log] param[15]=_FRAMEID=root
		return params;
	}

	@Override
	protected ResponseHandler<File> getResponseHandler() {
		return handler;
	}
}